package com.renli.servlet;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.renli.mapper.JobPositionMapper;
import com.renli.pojo.JobPosition;
import com.renli.servlet.common.BaseServlet;
import com.renli.utils.ApiResult;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/api/job_position")
public class JobPositionServlet extends BaseServlet {
    // 添加职位
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取请求的输入流
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        reader.close();

        // 使用 Jackson 将 JSON 数据映射到 JobPosition 对象
        ObjectMapper mapper = new ObjectMapper();
        JobPosition jobPosition = mapper.readValue(jsonBuilder.toString(), JobPosition.class);

        // 调用 JobPositionMapper 的 add 方法将职位信息添加到数据库
        try {
            boolean result = JobPositionMapper.add(jobPosition);
            if (result) {
                // 添加成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
            } else {
                // 添加失败
                sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 删除职位
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int positionId = Integer.parseInt(req.getParameter("id"));
        try {
            boolean result = JobPositionMapper.delete(positionId);
            if (result) {
                // 删除成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
            } else {
                // 删除失败
                sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 更新职位信息
    public void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取请求的输入流
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        reader.close();

        // 使用 Jackson 将 JSON 数据映射到 JobPosition 对象
        ObjectMapper mapper = new ObjectMapper();
        JobPosition jobPosition = mapper.readValue(jsonBuilder.toString(), JobPosition.class);

        try {
            boolean result = JobPositionMapper.update(jobPosition);
            if (result) {
                // 更新成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
            } else {
                // 更新失败
                sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 根据职位ID获取职位信息
    public void getJobPositionById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int positionId = Integer.parseInt(req.getParameter("positionId"));
        try {
            JobPosition jobPosition = JobPositionMapper.getJobPositionById(positionId);
            if (jobPosition != null) {
                // 获取成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, jobPosition));
            } else {
                // 职位不存在
                sendJsonResponse(resp, new ApiResult<>(1, "职位不存在", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 分页查询职位列表（根据职位名称模糊搜索）
    public void getJobPositionsByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String positionName = req.getParameter("searchParams");
        int pageNum = Integer.parseInt(req.getParameter("page"));
        int pageSize = Integer.parseInt(req.getParameter("limit"));

        try {
            List<JobPosition> jobPositions = JobPositionMapper.getJobPositionsByPage(positionName, pageNum, pageSize);
            int totalRecordCount = JobPositionMapper.getTotalJobPositionCount(); // 获取记录总数

            if (totalRecordCount > 0) {
                // 查询成功，返回记录总数和职位列表
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", totalRecordCount, jobPositions));
            } else {
                // 职位不存在
                sendJsonResponse(resp, new ApiResult<>(1, "职位不存在", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 批量删除职位
    public void deleteBatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 从请求的输入流中获取JSON数据
            BufferedReader reader = req.getReader();
            StringBuilder jsonBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }

            // 使用 Jackson 将 JSON 数据解析为数组
            ObjectMapper mapper = new ObjectMapper();
            List<Integer> positionIds = mapper.readValue(jsonBuilder.toString(), new TypeReference<List<Integer>>() {
            });

            if (positionIds != null && !positionIds.isEmpty()) {
                boolean result = JobPositionMapper.batchDelete(positionIds);
                if (result) {
                    // 删除成功
                    sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
                } else {
                    // 删除失败
                    sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
                }
            } else {
                // 参数错误
                sendJsonResponse(resp, new ApiResult<>(1, "参数错误", null, null));
            }
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 获取所有职位列表
    public void getAllJobPositions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            List<JobPosition> jobPositions = JobPositionMapper.getAllJobPositions();
            if (!jobPositions.isEmpty()) {
                // 查询成功，返回职位列表
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, jobPositions));
            } else {
                // 职位列表为空
                sendJsonResponse(resp, new ApiResult<>(1, "职位列表为空", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

}
